﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml;
using System.Text.RegularExpressions;


    public class PlayerAPI
    {
        public Player GetByQuery(string name)
        {
            var SearchResultUrl = "http://svenskfotboll.se/sok/?q=" + name + "&search-type=0";
            var SearchDOM = new DOM(SearchResultUrl);
            if (SearchDOM != null)
            {

                var PlayerUrls = Regex.Match(SearchDOM.Html, "<a href=\"(http://svenskfotboll.se/.*/person/.playerid=\\d*)\"");

                if (PlayerUrls.Success)
                {
                    string PlayerProfileUrl = PlayerUrls.Groups[1].Value;

                    return GetPlayerProfile(PlayerProfileUrl);

                }

            }
            else
            {
                return null;
            }


            return null;
        }

        private Player GetPlayerProfile(string url)
        {
            var Document = new DOM(url);
            Player player = new Player();

            player.Id = Regex.Match(url, "playerid=(\\d*)").Groups[1].Value;
            player.Permalink = url;
            player.Name = Document.DocumentModel.SelectSingleNode("//h1[@class='h']").InnerText;
            player.ImageUrl = "http://svenskfotboll.se" + Document.DocumentModel.SelectSingleNode("//div[@class='player-image']/img/@src").InnerText;

            var TableRows = Document.DocumentModel.SelectNodes("//table[@class='clTblStatBox']//tr");

            player.ShirtNumber = Document.DocumentModel.SelectSingleNode("//table[@class='clTblStatBox']//thead").InnerText;
            player.ShirtNumber = Regex.Match(player.ShirtNumber, "Nr (\\d*)").Groups[1].Value;

            player.BirthDate = TableRows.GetCellValueByFirstColumn("Född:");

            var HeightAndWeight = TableRows.GetCellValueByFirstColumn("Längd/Vikt:");
            if (HeightAndWeight.Contains("/"))
            {
                player.Height = HeightAndWeight.Split('/')[0];
                player.Weight = HeightAndWeight.Split('/')[1];
            }

            player.MotherClub = TableRows.GetCellValueByFirstColumn("Moderklubb:");

            return player;
        }

    }
